package com.pzh.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.usercenter.common.BaseResponse;
import com.pzh.usercenter.common.DeleteRequest;
import com.pzh.usercenter.common.ErrorCode;
import com.pzh.usercenter.common.ResultUtils;
import com.pzh.usercenter.exception.BusinessException;
import com.pzh.usercenter.model.domain.Team;
import com.pzh.usercenter.model.domain.User;
import com.pzh.usercenter.model.domain.UserTeam;
import com.pzh.usercenter.model.dto.TeamQuery;
import com.pzh.usercenter.model.request.JoinTeamRequest;
import com.pzh.usercenter.model.request.QuitTeamRequest;
import com.pzh.usercenter.model.request.TeamAddRequest;
import com.pzh.usercenter.model.request.TeamUpdateRequest;
import com.pzh.usercenter.model.vo.TeamUserVO;
import com.pzh.usercenter.service.TeamService;
import com.pzh.usercenter.service.UserService;
import com.pzh.usercenter.service.UserTeamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@Tag(name = "队伍接口")
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    @Operation(summary = "创建队伍")
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if(teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        Long addTeamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(addTeamId);
    }

    @Operation(summary = "根据teamId删除队伍")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if(deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long teamId = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        boolean removed = teamService.deleteTeam(teamId,loginUser);
        if(!removed) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return ResultUtils.success(true);
    }

    @Operation(summary = "更新队伍")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if(teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest,loginUser);
        if(!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return ResultUtils.success(true);
    }

    @Operation(summary = "根据teamId获取队伍信息")
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(Long teamId) {
        if(teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(teamId);
        if(team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    @Operation(summary = "根据条件查询队伍")
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> getTeamList(TeamQuery teamQuery,HttpServletRequest request) {
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        List<TeamUserVO> list = teamService.listTeams(teamQuery,isAdmin);
        List<Long> teamIdList = list.stream().map(TeamUserVO::getId).toList();

        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        try {
            //若用户已登录
            User loginUser = userService.getLoginUser(request);
            queryWrapper.eq("userId",loginUser.getId());
            queryWrapper.in("teamId",teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
            //已加入的队伍id集合
            Set<Long> hasTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            list.forEach(team -> {
                boolean contains = hasTeamIdSet.contains(team.getId());
                team.setHasJoin(contains);
            });
        } catch (Exception e) {
            //未登录抛异常不做处理
        }
        //查询已加入的用户个数
        QueryWrapper<UserTeam> queryUserJoinNums = new QueryWrapper<>();
        queryUserJoinNums.in("teamId",teamIdList);
        List<UserTeam> userTeams = userTeamService.list(queryUserJoinNums);
        //Map : 队伍id => 加入该队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserList = userTeams.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        list.forEach(team ->  team.setHasJoinNum(teamIdUserList.getOrDefault(team.getId(),new ArrayList<>()).size()));
        return ResultUtils.success(list);
    }

    @Operation(summary = "获取我创建的队伍")
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeam(TeamQuery teamQuery,HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> list = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(list);
    }

    @Operation(summary = "获取我加入的队伍")
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeam(TeamQuery teamQuery,HttpServletRequest request) {
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        List<UserTeam> teamIdList = userTeamService.list(queryWrapper);
        //变为仅为teamId的集合
        Map<Long, List<UserTeam>> collect = teamIdList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        ArrayList<Long> idLists = new ArrayList<>(collect.keySet());
        teamQuery.setIdList(idLists);
        List<TeamUserVO> list = teamService.listTeams(teamQuery,true);
        return ResultUtils.success(list);
    }

    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> getTeamListByPage(TeamQuery teamQuery) {
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        // todo teamList是否需要改动？
        BeanUtils.copyProperties(teamQuery, team);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(),teamQuery.getPageSize());
        Page<Team> resultPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(resultPage);
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody JoinTeamRequest joinTeamRequest,HttpServletRequest request) {
        if(joinTeamRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result =  teamService.joinTeam(joinTeamRequest,loginUser);
        if(!result) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(true);
    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody QuitTeamRequest quitTeamRequest, HttpServletRequest request) {
        if(quitTeamRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result =  teamService.quitTeam(quitTeamRequest,loginUser);
        if(!result) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(true);
    }

}
